# coding=utf-8
# -*- coding: utf-8 -*-

import os
import sys
import jinja2
import pytz, time
import datetime
import openerp
import simplejson
import werkzeug.utils
from openerp import http
from openerp.http import request
from openerp.osv import fields, osv
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug

ISODATEFORMAT = '%Y-%m-%d'
ISODATETIMEFORMAT = "%Y-%m-%d %H:%M:%S"
SUPERUSER_ID = 1

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


class HrController(http.Controller):
    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps

    def raise_error(func):
        try:
            return_value = func()
        except Exception:
            return {'messge': 'error'}
        return return_value

    def _parse_int(self, parsed_value):
        try:
            parse_value = int(parsed_value)
        except ValueError:
            # TODO 应该需要返回一个错误的response
            raise osv.except_osv(u'错误', u'遇到一个无法解析的id')

        return parse_value

    @http.route(['/wx/hr/<string:type>/<string:approve_type>'], auth='weixin')
    def add_work_overtime_leave(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        kw = {}
        if args.get('id'):
            cr.execute("""""")
        else:
            kw = {'user_name': "系统管理员", 'user_id': 1, }
        kw.update({'type': args.get('type'),
                  'approve_type': args.get('approve_type')})
        template = env.get_template("hr/first_page.html")
        return template.render(kw)

    def get_filed_value(self, cr, uid, onefield, context=None):
        if onefield.get('type_detail') == 'datetime-local':
            time_stamp = datetime.datetime.strptime(onefield.get('value'), '%Y-%m-%dT%H:%M:%S.%fZ')
            time_stamp = time_stamp # - datetime.timedelta(hours=8)
            return time_stamp.strftime('%Y-%m-%d %H:%M:%S')
        if onefield.get('type') in ('input', 'textarea'):
            return_value = onefield.get('value')
        elif onefield.get('type') == 'checkbox':
            reconcile_values_ids = onefield.get('value_range')
            reconcile_ids = [reconcile_values_ids[index].get('id') for index in onefield.get('value')]
            return_value = [[6, False, reconcile_ids]]
        else:
            return_value = onefield.get('value')
        if onefield.get('type_detail') == 'number':
            return_value = round(float(return_value), 1)
        return return_value

    @http.route('/wx/hr/new_ask_for_leave', auth='weixin', type='json')
    def new_ask_for_leave(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        try:
            all_data = request.jsonrequest.get('all_fields')
            recrord_type = request.jsonrequest.get('model_type')
            create_data = {}
            uid = request.session.get('uid')
            [create_data.update({onefield.get('field_name'): self.get_filed_value(cr, uid, onefield, context=context)})
             for onefield in all_data]
            create_data.update({'user_id': uid, 'type': 'overtime' if recrord_type == 'work' else 'changeworkday'})
            create_data.update(pool.get('work.overtime.leave').get_approve_user_id(cr, uid, uid, context=context))
            if not pool.get('work.overtime.leave').check_time_have_repeat(cr, 1, create_data, context=context):
                if create_data.get('id', False):
                    create_id = pool.get('work.overtime.leave').write(cr, 1, int(create_data.get('id')),
                                                                      create_data, context=context)
                else:
                    create_id = pool.get('work.overtime.leave').create(cr, 1, create_data, context=context)
                return simplejson.dumps({'create_id': create_id})
            else:
                # print "----------------------滴！提交成功就说明有BUG了！"
                cr.rollback()
                return simplejson.dumps({'errMsg': u'申请时间段重叠或者部分重叠'})
        except Exception as e:
            # print "----------------------滴！提交成功就说明有BUG了！"
            cr.rollback()
            if e and e.value:
                return simplejson.dumps({'errMsg': u'%s' % e.value})
            else:
                return simplejson.dumps({'errMsg': u'新建错误联系管理员'})

    def handling_time(self, datetime_str):
        time_stamp = datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        time_stamp = time_stamp + datetime.timedelta(hours=8)
        return time_stamp.strftime('%Y-%m-%d %H:%M:%S')

    def get_show_message(self, cr, uid, leave, approve_type, leave_type, pool, context=None):
        return_list = [{'label': '编号', 'value': leave.id,  'invisible': True},
                       {'label': '审批状态', 'value': self.get_approve_flag(cr, uid, leave, context=context),
                        'approve_flag': True},
                       {'label': '申请小时数', 'value': round(leave.hour_qty, 1)},
                       {'label': '开始时间', 'value': self.handling_time(leave.start_time)},
                       {'label': '结束时间', 'value': self.handling_time(leave.end_time)},
                       {'label': '备注', 'value': leave.note}
                       ]
        if leave.type == 'overtime':
            weixin_uid = pool.get('weixin.contacts').search(cr, SUPERUSER_ID, [('odoo_user_id', '=', leave.user_id.id)], context=context)
            date_str = leave.start_time[0:10]
            punch_ids = pool.get('weixin.punch').search(cr, SUPERUSER_ID, [('userid', '=', weixin_uid and weixin_uid[0]),
                                                                    ('date', '>=', "%s 00:00:00" % date_str),
                                                                    ('date', '<', '%s 23:59:59' % date_str)], context=context)
            punch_str, have_punch = [], False
            for punch in pool.get('weixin.punch').browse(cr, SUPERUSER_ID, punch_ids, context=context):
                time_str = time.strftime('%Y-%m-%d %H:%M:%S',  time.localtime(int(punch.checkin_time) + 28800))
                return_list.insert(7, {'label': punch.checkin_type, 'value': time_str})
                have_punch = True
            if not have_punch:
                 return_list.insert(7, {'label': '上班打卡', 'value': '无'})
                 return_list.insert(7, {'label': '下班打卡', 'value': '无'})
        if approve_type != 'all':
            return_list.insert(1, {'label': '姓名', 'value': leave.user_id.name})
        else:
            return_list.insert(3, {'label': '审批人', 'value': leave.approver_user_id.name})
        return return_list

    @http.route('/wx/hr/get_ask_for_leave', auth='weixin', type='http', methods=['GET'])
    def get_ask_for_leave(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        uid = request.session.get('uid')
        leave_type = request.params.get('type')
        users_obj = pool.get('res.users')
        approve_type = request.params.get('unapprove')
        if leave_type == 'work':
            doamin = [('type', '=', 'overtime')]
        else:
            doamin = [('type', '=', 'changeworkday')]
        if approve_type == 'unapprove':
            doamin += [('is_approve', '=', False), ('approver_user_id', '=', uid), ('is_refuse', '=', False)]
        elif approve_type == 'approve':
            if not users_obj.has_group(cr, uid, 'base.group_hr_user'):
                doamin += [('approver_user_id', '=', uid), ('is_approve', '=', True)]
            else:
                doamin += [('create_uid', '=', '0')]
        elif approve_type == 'other_approve':
            if users_obj.has_group(cr, uid, 'base.group_hr_user'):
                doamin += [('is_approve', '=', True)]
            else:
                doamin += [('create_uid', '=', '0')]
        else:
            doamin += [('user_id', '=', uid)]
        leave_ids = pool.get('work.overtime.leave').search(cr, 1, doamin, limit=4,
                                                           offset=(int(request.params.get('offset'))),
                                                           order='create_date desc', context=context)
        leave_rows = pool.get('work.overtime.leave').browse(cr, 1, leave_ids, context=context)
        return_vals = [self.get_show_message(cr, uid, leave, approve_type, leave_type, pool, context=context)
                       for leave in leave_rows]
        return simplejson.dumps(return_vals)

    def get_approve_flag(self, cr, uid, leave, context=None):
        if not (leave.is_approve or leave.is_refuse):
            approve_flag = 0
        elif leave.is_approve:
            approve_flag = 1
        elif leave.is_refuse:
            approve_flag = -1
        return approve_flag

    @http.route('/wx/hr/get_ask_leave_fields', auth='weixin', type='http', methods=['GET'])
    def get_ask_leave_fields(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        uid = request.session.get('uid')
        leave_obj = pool.get('work.overtime.leave')
        leave_id = request.params.get('id', False)
        leave_row = leave_obj.browse(cr, uid, leave_id and int(leave_id), context=context)
        user_row = pool.get('res.users').browse(cr, 1, uid, context=context)
        return_vals = [{'str': '姓名', 'type_detail': 'text', 'pattern': '.?', 'field_name': 'create_user_name',
                        'required': True, 'value': user_row.name, 'disabled': "disabled", 'type': 'input',
                        'compute_value': False},
                       {'str': '开始时间', 'type_detail': 'datetime-local', 'field_name': 'start_time',
                        'value': leave_id and self.handling_time(leave_row.start_time) or '',
                        'required': True, 'type': 'input', 'compute_value': False},
                       {'str': '结束时间', 'type_detail': 'datetime-local', 'field_name': 'end_time',
                        'value': leave_id and self.handling_time(leave_row.end_time) or '',
                        'required': True, 'type': 'input', 'compute_value': False},
                       {'str': '时长', 'type_detail': 'number', 'pattern': '[0-9]*\.',
                        'value':  leave_id and leave_row.hour_qty or '',
                        'compute_value': False,
                        'field_name': 'hour_qty', 'required': True, 'type': 'input', 'compute_value': False},
                       {'str': '详情', 'type_detail': 'textarea', 'field_name': 'note',
                        'value': leave_id and leave_row.note or '',
                        'required': True, 'type': 'textarea', 'compute_value': False},
                       {'str': 'ID', 'type_detail': 'textarea', 'field_name': 'id', 'value': leave_id,
                        'required': False, 'type': 'textarea', 'compute_value': False, 'invisible': True},
                       {'str': '修改时间', 'type_detail': 'textarea', 'field_name': 'write_date',
                        'value': leave_id and leave_row.write_date or False,
                        'required': False, 'type': 'textarea', 'compute_value': False, 'invisible': True},
                       ]
        if request.params.get('type') == 'leave':
            return_vals.insert(5, {'str': '选择加班', 'field_name': 'reconcile_ids',
                                   'value': [],
                                   'type': 'checkbox', 'required': True,
                                   'value_range': self.get_reconcile_ids_values(pool,
                                    cr, uid, [leave.id for leave in leave_row.reconcile_ids], context=context)})
        return simplejson.dumps(return_vals)

    def get_reconcile_ids_values(self, pool, cr, uid, leave_ids, context=None):
        leave_obj = pool.get('work.overtime.leave')
        now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        reconcile_value_ids = leave_obj.search(cr, 1, [('type', 'in', ('overtime', 'annual_leave')),
                                                       ('is_approve', '=', True),
                                                       ('user_id', '=', uid),
                                                       ('is_refuse', '=', False),
                                                       ('residue_qty', '!=', 0),
                                                       '|', ('expire_date', '>=', now_date),
                                                       ('expire_date', '=', False)
                                                       ],
                                               order='expire_date',
                                               context=context)
        reconcile_value = []
        for leave_row in leave_obj.browse(cr, 1, reconcile_value_ids, context=context):
            if leave_row.type == 'overtime':
                show_str = "加班(%s／%s小时)[%s过期]" % (leave_row.residue_qty, leave_row.hour_qty,
                                                  leave_row.expire_date if leave_row.expire_date else '永久不')
            elif leave_row.type == 'annual_leave':
                show_str = "年假(%s／%s小时)[%s过期]" % (leave_row.residue_qty, leave_row.hour_qty,
                                                  leave_row.expire_date if leave_row.expire_date else '永久不')
            reconcile_value.append({'id': leave_row.id,
                                    'str': show_str,
                                    'checked': 'off', 'hours': leave_row.residue_qty})
        return reconcile_value

    @http.route('/wx/hr/approver_work_or_leave', auth='weixin', type='json')
    def approver_work_or_leave(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        record_id = request.jsonrequest.get('record_id')
        uid = request.session.get('uid')
        pool.get('work.overtime.leave').approve_agree(cr, uid, int(record_id), context=context)
        return simplejson.dumps({})

    @http.route('/wx/hr/refuse_work_or_leave', auth='weixin', type='json')
    def refuse_work_or_leave(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        record_id = request.jsonrequest.get('record_id')
        uid = request.session.get('uid')
        pool.get('work.overtime.leave').approve_refuse(cr, uid, int(record_id), context=context)
        return simplejson.dumps({})

    @http.route('/wx/hr/delete_work_or_leave', auth='weixin', type='json')
    def delete_work_or_leave(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        record_id = request.jsonrequest.get('record_id')
        uid = request.session.get('uid')
        pool.get('work.overtime.leave').unlink(cr, uid, int(record_id), context=context)
        return simplejson.dumps({})

    @http.route('/wx/hr/get_user_group_message', auth='weixin', type='http', methods=['GET'])
    def get_user_group_message(self, **args):
        cr, context, pool = request.cr, request.context, request.registry
        uid = request.session.get('uid')
        if pool.get('res.users').has_group(cr, uid, 'base.group_hr_user'):
            return simplejson.dumps(0)
        if pool.get('work.overtime.leave').search(cr, SUPERUSER_ID, [('approver_user_id', '=', uid),
                                                            ('is_approve', '=', True)], context=context):
            return simplejson.dumps(1)
        return simplejson.dumps(-1)

    @http.route('/wx/hr/get_unapprove_num_ask_leave', auth='weixin', type='http', methods=['GET'])
    def get_unapprove_num_ask_leave(self, **args):
        # 获取需要审批的单据的数量
        cr, context, pool = request.cr, request.context, request.registry
        uid = request.session.get('uid')
        leave_obj = pool.get('work.overtime.leave')
        if request.params.get('type') == 'work':
            reconcile_value_ids = leave_obj.search(cr, 1, [('type', '=', 'overtime'),
                                                           ('is_approve', '=', False),
                                                           ('is_refuse', '=', False),
                                                           ('approver_user_id', '=', uid)],
                                                   context=context)
        else:
            reconcile_value_ids = leave_obj.search(cr, 1, [('type', '=', 'changeworkday'),
                                                           ('is_approve', '=', False),
                                                           ('is_refuse', '=', False),
                                                           ('approver_user_id', '=', uid)],
                                                   context=context)
        return simplejson.dumps(len(reconcile_value_ids))
